<template>
  <div class="product-member-container">
    <h2>产品人员管理</h2>
    <p>管理产品的团队成员，分配不同角色权限</p>
    
    <!-- 产品选择 -->
    <div class="product-selection">
      <el-select
        v-model="searchForm.productId"
        placeholder="请选择产品"
        style="width: 300px"
        @change="handleProductChange"
      >
        <el-option
          v-for="product in productOptions"
          :key="product.id"
          :label="product.productName"
          :value="product.id"
        ></el-option>
      </el-select>
      
      <el-button type="primary" @click="handleRefresh">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>
    
    <!-- 人员管理区域 -->
    <div v-if="selectedProductId" class="member-management">
      <!-- 成员统计 -->
      <div class="member-stats">
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ currentMembers.length }}</div>
            <div class="stat-label">总成员数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ roleStats.productOwner }}</div>
            <div class="stat-label">产品负责人</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ roleStats.testOwner }}</div>
            <div class="stat-label">测试负责人</div>
          </div>
        </div>
      </div>
      
      <!-- 当前成员列表 -->
      <div class="current-members">
        <el-input
          v-model="memberSearch"
          placeholder="搜索成员姓名/用户名"
          prefix-icon="Search"
          style="width: 250px; margin-bottom: 16px"
          clearable
        ></el-input>
        
        <el-button type="primary" @click="showAddMemberDialog" style="margin-bottom: 16px">
          <el-icon><Plus /></el-icon>
          添加成员
        </el-button>
        
        <el-table
          :data="filteredMembers"
          style="width: 100%"
          border
          v-loading="loading"
        >
          <el-table-column prop="userId" label="用户ID" width="80"></el-table-column>
          <el-table-column prop="username" label="用户名" width="120"></el-table-column>
          <el-table-column prop="realName" label="姓名" width="120"></el-table-column>
          <el-table-column prop="role" label="角色" width="150">
            <template #default="scope">
              <el-tag :type="getRoleType(scope.row.role)">
                {{ getRoleName(scope.row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="joinTime" label="加入时间" width="180"></el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditMember(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleRemoveMember(scope.row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 空状态 -->
        <div v-if="currentMembers.length === 0 && !loading" class="empty-members">
          <el-empty description="暂无产品成员" />
        </div>
      </div>
    </div>
    
    <!-- 未选择产品提示 -->
    <div v-else class="no-selection">
      <el-empty description="请选择产品以查看和管理成员" />
    </div>
    
    <!-- 添加/编辑成员对话框 -->
    <el-dialog
      v-model="memberDialog.visible"
      :title="memberDialog.title"
      width="500px"
    >
      <el-form ref="memberForm" :model="memberForm" :rules="memberRules" label-width="100px">
        <el-form-item prop="userId" label="用户">
          <el-select v-model="memberForm.userId" placeholder="请选择用户">
            <el-option
              v-for="user in availableUsers"
              :key="user.id"
              :label="user.realName + '(' + user.username + ')'"
              :value="user.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="role" label="角色">
          <el-select v-model="memberForm.role" placeholder="请选择角色">
            <el-option label="产品负责人" value="PRODUCT_OWNER"></el-option>
            <el-option label="测试负责人" value="TEST_OWNER"></el-option>
            <el-option label="产品参与人员" value="PRODUCT_MEMBER"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="memberDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitMember">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'

// 移除完整的echarts导入，简化页面

export default {
  name: 'ProductMemberManager',
  components: {
    Plus,
    Search,
    Refresh
  },
  setup() {
    const searchForm = ref({
      productId: ''
    })
    
    const productOptions = ref([])
    const selectedProductId = ref('')
    const currentMembers = ref([])
    const availableUsers = ref([])
    
    const memberDialog = ref({
      visible: false,
      title: '添加产品成员'
    })
    
    const memberForm = ref({
      id: '',
      productId: '',
      userId: '',
      role: ''
    })
    
    const memberRules = ref({
      userId: [{ required: true, message: '请选择用户', trigger: 'blur' }],
      role: [{ required: true, message: '请选择角色', trigger: 'blur' }]
    })
    
    // 简化数据变量
    const loading = ref(false)
    const memberSearch = ref('')
    const roleStats = reactive({
      productOwner: 0,
      testOwner: 0,
      productMember: 0
    })
    
    // 角色映射
    const roleMap = {
      PRODUCT_OWNER: { name: '产品负责人', type: 'primary' },
      TEST_OWNER: { name: '测试负责人', type: 'success' },
      PRODUCT_MEMBER: { name: '产品参与人员', type: 'info' }
    }
    
    // 过滤后的成员列表
    const filteredMembers = computed(() => {
      if (!memberSearch.value.trim()) {
        return currentMembers.value
      }
      const searchText = memberSearch.value.toLowerCase().trim()
      return currentMembers.value.filter(member => 
        member.realName.toLowerCase().includes(searchText) ||
        member.username.toLowerCase().includes(searchText)
      )
    })
    
    // 初始化数据
    onMounted(() => {
      fetchProductOptions()
    })
    
    // 获取产品列表选项
    const fetchProductOptions = async () => {
      try {
        // 使用模拟数据以避免API调用
        productOptions.value = [
          { id: 1, productName: '测试系统A' },
          { id: 2, productName: '测试系统B' },
          { id: 3, productName: '测试系统C' }
        ]
      } catch (error) {
        console.error('获取产品列表失败:', error)
        ElMessage.error('获取产品列表失败')
      }
    }
    
    // 处理产品选择变化
    const handleProductChange = (productId) => {
      selectedProductId.value = productId
      if (productId) {
        fetchProductMembers(productId)
        fetchAvailableUsers(productId)
      } else {
        currentMembers.value = []
        availableUsers.value = []
        resetRoleStats()
      }
    }
    
    // 获取产品成员列表
    const fetchProductMembers = async (productId) => {
      loading.value = true
      try {
        // 根据不同产品ID返回不同的模拟数据
        if (productId === 1) {
          // 测试系统A的成员数据
          currentMembers.value = [
            {
              id: 101,
              userId: 101,
              username: 'zhangshan_a',
              realName: '张山',
              role: 'PRODUCT_OWNER',
              joinTime: '2025-08-10 09:00:00'
            },
            {
              id: 102,
              userId: 102,
              username: 'lihua_a',
              realName: '李华',
              role: 'TEST_OWNER',
              joinTime: '2025-08-11 14:30:00'
            },
            {
              id: 103,
              userId: 103,
              username: 'wangming_a',
              realName: '王明',
              role: 'PRODUCT_MEMBER',
              joinTime: '2025-08-15 11:20:00'
            }
          ]
        } else if (productId === 2) {
          // 测试系统B的成员数据
          currentMembers.value = [
            {
              id: 201,
              userId: 201,
              username: 'zhaoyang_b',
              realName: '赵阳',
              role: 'PRODUCT_OWNER',
              joinTime: '2025-08-05 10:15:00'
            },
            {
              id: 202,
              userId: 202,
              username: 'sulin_b',
              realName: '苏琳',
              role: 'TEST_OWNER',
              joinTime: '2025-08-08 16:40:00'
            },
            {
              id: 203,
              userId: 203,
              username: 'chenfei_b',
              realName: '陈飞',
              role: 'PRODUCT_MEMBER',
              joinTime: '2025-08-12 09:30:00'
            },
            {
              id: 204,
              userId: 204,
              username: 'yangyang_b',
              realName: '杨洋',
              role: 'PRODUCT_MEMBER',
              joinTime: '2025-08-20 13:50:00'
            }
          ]
        } else if (productId === 3) {
          // 测试系统C的成员数据
          currentMembers.value = [
            {
              id: 301,
              userId: 301,
              username: 'huangwei_c',
              realName: '黄伟',
              role: 'PRODUCT_OWNER',
              joinTime: '2025-07-25 14:20:00'
            },
            {
              id: 302,
              userId: 302,
              username: 'wuxia_c',
              realName: '吴霞',
              role: 'TEST_OWNER',
              joinTime: '2025-07-30 09:10:00'
            },
            {
              id: 303,
              userId: 303,
              username: 'zhaohui_c',
              realName: '赵辉',
              role: 'PRODUCT_MEMBER',
              joinTime: '2025-08-05 15:45:00'
            },
            {
              id: 304,
              userId: 304,
              username: 'qianqian_c',
              realName: '钱茜',
              role: 'PRODUCT_MEMBER',
              joinTime: '2025-08-10 11:30:00'
            },
            {
              id: 305,
              userId: 305,
              username: 'sunny_c',
              realName: '孙妮',
              role: 'PRODUCT_MEMBER',
              joinTime: '2025-08-15 16:20:00'
            }
          ]
        }
        updateRoleStats(currentMembers.value)
      } catch (error) {
        console.error('获取产品成员失败:', error)
        ElMessage.error('获取产品成员失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取可添加的用户列表
    const fetchAvailableUsers = async (productId) => {
      try {
        // 使用模拟数据以避免API调用
        availableUsers.value = [
          { id: 5, username: 'sunqi', realName: '孙七' },
          { id: 6, username: 'zhouba', realName: '周八' },
          { id: 7, username: 'wujiu', realName: '吴九' }
        ]
      } catch (error) {
        console.error('获取可添加用户失败:', error)
        ElMessage.error('获取可添加用户失败')
      }
    }
    
    // 刷新
    const handleRefresh = () => {
      if (selectedProductId.value) {
        fetchProductMembers(selectedProductId.value)
        fetchAvailableUsers(selectedProductId.value)
        ElMessage.success('刷新成功')
      } else {
        fetchProductOptions()
        ElMessage.success('刷新成功')
      }
    }
    
    // 显示添加成员对话框
    const showAddMemberDialog = () => {
      memberDialog.value.title = '添加产品成员'
      memberForm.value = {
        id: '',
        productId: selectedProductId.value,
        userId: '',
        role: ''
      }
      memberDialog.value.visible = true
    }
    
    // 处理编辑成员
    const handleEditMember = (row) => {
      memberDialog.value.title = '编辑产品成员'
      memberForm.value = { ...row }
      memberDialog.value.visible = true
    }
    
    // 提交成员表单
    const handleSubmitMember = () => {
      // 简单的表单验证
      if (!memberForm.value.userId || !memberForm.value.role) {
        ElMessage.warning('请填写完整信息')
        return
      }
      
      if (memberForm.value.id) {
        // 编辑模式
        const index = currentMembers.value.findIndex(item => item.id === memberForm.value.id)
        if (index !== -1) {
          currentMembers.value[index] = { ...memberForm.value }
          ElMessage.success('编辑成功')
        }
      } else {
        // 添加模式
        const newMember = {
          id: Date.now(), // 临时ID
          ...memberForm.value,
          username: availableUsers.value.find(u => u.id === memberForm.value.userId)?.username || '',
          realName: availableUsers.value.find(u => u.id === memberForm.value.userId)?.realName || '',
          joinTime: new Date().toLocaleString('zh-CN')
        }
        currentMembers.value.push(newMember)
        ElMessage.success('添加成功')
      }
      
      updateRoleStats(currentMembers.value)
      memberDialog.value.visible = false
    }
    
    // 处理移除成员
    const handleRemoveMember = (row) => {
      const index = currentMembers.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        currentMembers.value.splice(index, 1)
        updateRoleStats(currentMembers.value)
        ElMessage.success('移除成功')
      }
    }
    
    // 更新角色统计
    const updateRoleStats = (members) => {
      resetRoleStats()
      members.forEach(member => {
        switch (member.role) {
          case 'PRODUCT_OWNER':
            roleStats.productOwner++
            break
          case 'TEST_OWNER':
            roleStats.testOwner++
            break
          case 'PRODUCT_MEMBER':
            roleStats.productMember++
            break
        }
      })
    }
    
    // 重置角色统计
    const resetRoleStats = () => {
      roleStats.productOwner = 0
      roleStats.testOwner = 0
      roleStats.productMember = 0
    }
    
    // 获取角色名称
    const getRoleName = (roleKey) => {
      return roleMap[roleKey]?.name || roleKey
    }
    
    // 获取角色类型
    const getRoleType = (roleKey) => {
      return roleMap[roleKey]?.type || 'default'
    }
    
    return {
      searchForm,
      productOptions,
      selectedProductId,
      currentMembers,
      availableUsers,
      memberDialog,
      memberForm,
      memberRules,
      loading,
      memberSearch,
      roleStats,
      filteredMembers,
      
      handleProductChange,
      handleRefresh,
      showAddMemberDialog,
      handleEditMember,
      handleSubmitMember,
      handleRemoveMember,
      getRoleName,
      getRoleType
    }
  }
}
</script>

<style scoped>
.product-member-container {
  padding: 20px;
}

.product-selection {
  margin-bottom: 20px;
}

.member-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}
</style>